package anshe.widget
{
	
	import anshe.event.AnsheKeyword;
	import anshe.event.AnsheNetEvent;
	import anshe.struct.*;
	
	import com.adobe.serialization.json.JSON;
	
	import flash.display.*;
	import flash.events.*;
	import flash.net.*;
	import flash.utils.Timer;
	
	import org.dstart.object.debug.FDebug;

	public class AnsheWebLoader extends Sprite
	{
		private static const GET_USER_INFO_DONE:String	= "getUserInfoDone";
			//	取得用户信息完毕
		
		private static const GET_ROOM_INFO_DONE:String	= "getRoomInfoDone";
			//	取得房间信息完毕  
		
		private static var checkUrl:String = "http://system.anshechung.com/checkOwn.php";
		private static var getUserInfoUrl:String = "http://system.anshechung.com/api/getuserinfo.php";

		public var mcWait:MovieClip;			//	连接到服务器等待文字
		
		private var swfPath:String;				//	需要下载的 SWF 文件的地址路径
		private var isDebug:Boolean;			//	是否显示调试框
		
		private var fDebug:FDebug;				//	FDebug 类对象实例
		private var swfLoader:AnsheSWFLoader;	//	AnsheSWFLoader 类实例
		
		private var initSwfDone:Boolean;		//	下载 SWF 及主菜单等相关初始化动作完毕
		private var initRoomDone:Boolean;		//	确定房间 RoomID 完毕
		private var initServerDone:Boolean;		//	连接服务器成功（仅当连接服务器成功后才开始下载游戏）
		
		protected var acsSprite:Object;		//	全局侦听对象，AnsheSprite 类实例
		protected var acsServer:Object;		//	AnsheServer 类实例
		
		protected var myName:String;		//	用于测试用的用户名
		
		private var waitTime:Number	= 2;		//	向 IMVU 取房间信息等待时间

		public function AnsheWebLoader(fName:String = null, isShowDebug:Boolean = false)
		{
			swfPath = fName;
			isDebug = isShowDebug;
			
			initSwfDone = false;
			initRoomDone = false;
			initServerDone = false;
			
			this.mcWait.gotoAndStop(1);	
			this.addEventListener(Event.ADDED_TO_STAGE, onShowToStage);
			this.addEventListener(GET_USER_INFO_DONE, onGetUserInfoDone);
			this.addEventListener(GET_ROOM_INFO_DONE, onGetRoomInfoDone);
		}
		
		//	当对象显示到舞台上时触发
		private function onShowToStage(e:Event):void
		{
			this.stage.scaleMode = StageScaleMode.NO_SCALE;
			this.stage.align = StageAlign.TOP_LEFT;

			acsSprite = AnsheGlobal.GetAcsSprite(this);
		}

		//	程序主体入口（继承于 ClientWidgets 类的主入口方法）
		public function InitLoader():void
		{			
			//	如果不存在 acsSprite 类对象，则创建该对象，并进行一系列的初始化等动作
			if(!acsSprite)
			{
				//	申请 AnsheSprite 类成员对象，用于记录相关参数信息
				//	默认会打开调试模式，正式发布时会清除 AnsheSprite 中的调试功能
				acsSprite = new AnsheSprite(isDebug);

				this.stage.addChild(DisplayObject(acsSprite));
				
				//	给当前使用的 FDebug 实例赋值
				this.fDebug = acsSprite.fDebug as FDebug;
				
				mcWait.gotoAndStop(1);			

				InitUserInfo();		//	开始读取用户数据
				CheckNetObject();	//	开始检测已经下载完毕的对象
			}
			else
			{
				// trace("发现 NC 已经连接正常");
				
				if(this.swfPath)
				{
					this.acsServer = AnsheGlobal.GetAcsServer(this);
					this.acsServer.LoadFiles(this.swfPath);
				}
				
				DeleteSWF();
			}
		}

		//------------------- 取得用户信息 -------------------------------

				
		//	初始化用户信息（此步骤为取得房间信息的前一步骤，仅针对）
		private function InitUserInfo():void
		{
			if(!myName)
			{
				acsSprite.myInfo.name = "Guest_user" + Math.floor(Math.random() * 999);
			}
			else
			{
				acsSprite.myInfo.name = myName;
			}
			acsSprite.myInfo.userID = "" + int(Math.random() * 999999);

			GetUserFace();
			
			this.traceError("userName:" + acsSprite.myInfo.userName);
			this.traceError("userNick:" + acsSprite.myInfo.userNick);
			this.traceError("userID:" + acsSprite.myInfo.userID);
			this.traceError("userData:" + acsSprite.myInfo.userData);
		}
		
		//	取得玩家头像及性别等相关信息
		private function GetUserFace():void
		{
			var webLVariables:URLVariables = new URLVariables();
			webLVariables.id = acsSprite.myInfo.userID;
			
			var loginURLRequest:URLRequest = new URLRequest(getUserInfoUrl);
			loginURLRequest.method = URLRequestMethod.POST;
			loginURLRequest.data = webLVariables;

			var loginURLLoader:URLLoader = new URLLoader();
			loginURLLoader.addEventListener(Event.COMPLETE,loadUserInfoComplete);
			loginURLLoader.addEventListener (SecurityErrorEvent.SECURITY_ERROR,loadError);
			loginURLLoader.addEventListener(IOErrorEvent.IO_ERROR,loadError);
			loginURLLoader.dataFormat = URLLoaderDataFormat.TEXT;
			
			loginURLLoader.load(loginURLRequest);
		}
		
		//	当玩家信息读取完毕时触发
		private function loadUserInfoComplete(e:Event = null):void
		{
			var response:Object = JSON.decode(e.target.data);
			if(response['error'])
			{
				// throw new Error(response['error']);
			}
			else
			{
				var userInfo:Object = response['result'];
				this.acsSprite.myInfo.userFace = userInfo.picUrl;
				
				if(this.acsSprite.myInfo.userData.length > 0)
				{
					var tArray:Array = this.acsSprite.myInfo.userData.substr(1, this.acsSprite.myInfo.userData.length - 2).split(",");
					this.acsSprite.myInfo.isGirl = !Boolean(Number(tArray[0]) == 191);
				}					
				
				this.traceError("userFace:" + this.acsSprite.myInfo.userFace);
				this.traceError("isGirl:" + this.acsSprite.myInfo.isGirl);
				
				this.dispatchEvent(new Event(GET_USER_INFO_DONE));				
			}
		}
		
		//	当玩家信息读取失败时触发
		private function loadError(e:Event = null):void
		{
			traceError("LoadUserInfo Error! [ " + e + " ]");			
			
			this.dispatchEvent(new Event(GET_USER_INFO_DONE));
		}


		//-------------------- 取得房间信息 -----------------------
		
		
		//	取得用户信息完毕后触发
		private function onGetUserInfoDone(e:Event):void
		{
			this.removeEventListener(GET_USER_INFO_DONE, onGetUserInfoDone);			

			traceError("检测是否已经取得房间信息:: " + this.acsSprite.myRoom);
			
			//	如果房间信息还未取得，则创建房间信息对象并开始取得房间信息	
			this.acsSprite.myRoom.roomName = this.acsSprite.myInfo.userNick + "_" + this.acsSprite.myInfo.userID;			
			
			this.dispatchEvent(new Event(GET_ROOM_INFO_DONE));
		}

		//	取得房间信息后触发
		private function onGetRoomInfoDone(e:Event):void
		{
			this.removeEventListener(GET_ROOM_INFO_DONE, onGetRoomInfoDone);
			
			traceError("开始连接房间SO");
			traceInfo("myInfo::" + this.acsSprite.myInfo);
			traceInfo("roomInfo:" + this.acsSprite.myRoom);
			//try
			//{
				// this.space.removeEventListener(JOIN_ROOM, onGetJoinRoomEvent);
				// this.space.removeEventListener(CHECK_GLOBAL_SO, onGetRoomSoEvent);
				
				if(this.acsSprite.acsNetSpace)
				{
					traceInfo("要发送消息了... 当前:" + this.acsSprite.myInfo.userID, this.acsSprite.myInfo.userID.length);
					
					this.acsSprite.myRoom.roomName = "MyGameRoom";	
					
					if(!this.acsSprite.myInfo.userFace)
					{
						this.acsSprite.myInfo.userFace = "";
					}
					
					var infoArray:Array = new Array();
					infoArray.push(this.acsSprite.myInfo.imvuID);
					infoArray.push(this.acsSprite.myInfo.userName);
					infoArray.push(this.acsSprite.myInfo.userNick);
					infoArray.push(this.acsSprite.myInfo.userFace);
					infoArray.push(this.acsSprite.myInfo.isGirl);
					infoArray.push(this.acsSprite.myRoom.roomName);
					
					// trace("传出参数::" + infoArray);
					
					this.acsSprite.acsNetSpace.sendCommand(this, AnsheKeyword.REGISTER_SERVER, "onRegServer", false, true, infoArray);
					
					if(!this.acsSprite.acsNetSpace.soConnedted)
					{
						traceError("连接服务器 SO ：" + this.acsSprite.myRoom.roomName);	
											
						this.acsSprite.acsNetSpace.connGlobalSO(this.acsSprite.myRoom.roomName);
					}
				}
				else
				{
					this.traceError("还未连接服务器,等待服务器连接");
					
					var serverTime:Timer = new Timer(100);
					serverTime.addEventListener(TimerEvent.TIMER, onCheckServer);
					serverTime.start();
				}
			//}
			//catch(err:*)
			//{
			//	this.initSwfDone = true;
			//	traceError("InitRoomError");					
			//}
			
			this.initRoomDone = true;
			
			if(this.initRoomDone && this.initSwfDone)
			{
				DeleteSWF();
			}
		}
		
		private function onCheckServer(e:TimerEvent):void
		{
			// trace("继续检测服务器::" + this.acsSprite.acsNetSpace);
			if(this.acsSprite.acsNetSpace)
			{
				e.target.stop();
				e.target.removeEventListener(TimerEvent.TIMER, onCheckServer);
				
				onGetRoomInfoDone(null);
			}
		}	
		
		//	注册成功时触发
		public function onRegServer(argc:Array):void
		{
			initServerDone = true;
			
			traceError("LoginToServer OK:", argc);
			
			if(argc.length > 1)
			{
				this.acsSprite.myInfo.userID = argc[1];
				
				traceError("nowUserInfo::" + this.acsSprite.myInfo);
			}
			
			if(isLoadDone)
			{
				CheckDownLoadGame();
			}
		}		
		
		
		//-------------------- 判断文件及数据的下载 --------------------
		
		//	检测网络是否连接正常
		private function CheckNetObject():void
		{
			// trace("执行一次检测", this.acsSprite.acsNetSpace);
			if(this.acsSprite.acsNetSpace == undefined)
			{
				// trace("初始化 AnsheNetSpace 类对象");
				InitNetSpace();
			}
			else
			{
				// trace("开这里了，开始判断下载相关的部份：" + this.swfLoader);
				
				if(!this.swfLoader)
				{
					// trace("下载 AnsheSWFLoader.swf");
					LoadFiles("AnsheSWFLoader.swf");
				}
				else
				{
					// trace("找到 swfLoader ！");
					
					if(this.acsSprite.acsServer == undefined)
					{
						// trace("下载 AnsheServer.swf");
						mcWait.gotoAndStop(2);
						LoadFiles("AnsheServer.swf");
					}
					else
					{
						if(this.swfPath)
						{
							// trace("检测是否可以下载游戏");
							CheckDownLoadGame();
						}
						else
						{
							this.initSwfDone = true;
							
							if(this.initRoomDone && this.initSwfDone)
							{
								DeleteSWF();
							}
						}
					}
				}
			}
		}

		//	初始化网络连接对象
		private function InitNetSpace():void
		{
			this.acsSprite.acsNetSpace = new AnsheNetSpace();			
			this.stage.addChild(DisplayObject(this.acsSprite.acsNetSpace));
			
			this.stage.addEventListener(AnsheNetEvent.SERVER_CONN_COMPLETE, onConnDone);
			this.stage.addEventListener(AnsheNetEvent.SERVER_CONN_ERROR, onConnError);

			this.acsSprite.acsNetSpace.connServer();
		}
		
		private var nowLoadFileName:String;		//	当前下载的文件名称
		private var isLoadDone:Boolean;			//	是否下载文件已经结束
		
		//	成功连接到服务器后触发事件
		private function onConnDone(e:AnsheNetEvent):void
		{
			this.traceError("连接服务器成功");
			
			this.acsSprite.acsNetSpace.connGlobalSO("Room_abcc", "hello", 123);
			
			isLoadDone = false;
			
			this.stage.removeEventListener(AnsheNetEvent.SERVER_CONN_COMPLETE, onConnDone);
			this.stage.removeEventListener(AnsheNetEvent.SERVER_CONN_ERROR, onConnError);		

			this.acsSprite.acsNetSpace.addEventListener(AnsheNetEvent.LOAD_SWF_PRESS, onLoadSWfPress);
			this.acsSprite.acsNetSpace.addEventListener(AnsheNetEvent.LOAD_SWF_DONE, onLoadSWFDoneEvent);
			this.acsSprite.acsNetSpace.addEventListener(AnsheNetEvent.LOAD_SWF_ERROR, onLoadSWFErrorEvent);
			
			CheckNetObject();
		}
		
		private function LoadFiles(fileName:String):void
		{
			try
			{
				this.traceError("开始文件的下载>>> " + fileName);
				
				if(this.swfLoader)
				{
					this.swfLoader.percent = 0;
					this.swfLoader.visible = true;
				}
				
				nowLoadFileName = fileName;				
				this.acsSprite.acsNetSpace.DownloadSWF(nowLoadFileName);
			}
			catch(e:*)
			{
				traceError("准备下载文件时出错:" + e);
			}			
		}
		
		//	下载进度显示
		private function onLoadSWfPress(e:AnsheNetEvent):void
		{
			try
			{
				var swfData:SWFData = e.data[0] as SWFData;	
				// trace("downLoad..." + swfData);		
				if(swfData.swfName.toLowerCase() == nowLoadFileName.toLowerCase())
				{
					if(this.swfLoader)
					{
						this.swfLoader.percent = swfData.precent;
					}
				}
			}
			catch(err:*)
			{
				traceError("Loading data Error!" + err);
			}
		}
		
		//	文件下载完毕
		private function onLoadSWFDoneEvent(e:AnsheNetEvent):void
		{			
			try
			{
				var swfData:SWFData = e.data[0] as SWFData;
				
				traceError("下载文件完毕,文件大小:" + swfData.swfTotal + " 已经下载:" + swfData.swfLoad);
				
				if(swfData.swfName.toLowerCase() == nowLoadFileName.toLowerCase())
				{
					if(Math.floor(swfData.precent) >= 100)
					{
						if(this.swfLoader)
						{
							this.swfLoader.percent = 100;
							this.swfLoader.visible = false;
						}
						
						if(swfData.swfName.toLowerCase().indexOf(String("AnsheSWFLoader").toLowerCase()) >= 0)
						{
							// trace("保存 AnsheSWFLoader.swf 中的数据到内存");
							this.acsSprite.byteLoader = swfData.toByteArray();
						}
						
						var tLoad:Loader = new Loader();
						tLoad.contentLoaderInfo.addEventListener(Event.INIT, onInitSWFDone);						
						tLoad.loadBytes(swfData.toByteArray());
					}
					else
					{
						traceError("数据不完整...");
					}
				}
			}
			catch(err:*)
			{
				traceError("下载完毕,但处理时出错::" + err);
			}
		}
		
		private function onLoadSWFErrorEvent(e:AnsheNetEvent):void
		{
			this.traceError("下载游戏数据时出错::" + e.data);
		}
		
		private function onInitSWFDone(e:Event):void
		{
			e.target.removeEventListener(Event.INIT, onInitSWFDone);
			
			var spr:DisplayObject = e.target.content;
			this.stage.addChild(spr);
			
			if(spr is AnsheServer)
			{
				this.acsSprite.acsServer = spr as AnsheServer;
				spr.visible = false;

				this.mcWait.visible = true;
			}
			else if(spr is AnsheSWFLoader)
			{
				this.swfLoader = spr as AnsheSWFLoader
			}
			else if(spr is AnsheSuperClient)
			{
				this.acsSprite.acsServer.visible = true;
				spr.y = 30;// this.acsSprite.acsServer.height;
				
				(spr as AnsheSuperClient).server = this.acsSprite.acsNetSpace;
				(spr as AnsheSuperClient).InitGameListener();
			}
			
			// traceMessage("当前对象类型::" + spr);
			
			if(!isLoadDone)
			{
				CheckNetObject();
			}
			else
			{
				// spr.y = this.netServer.height + 2;						
				this.initSwfDone = true;
				if(this.initSwfDone && this.initRoomDone)
				{
					DeleteSWF();
				}
			}
		}
		
		//	连接服务器失败后触发事件
		private function onConnError(e:AnsheNetEvent):void
		{
			traceError("连接服务器失败",e.data);
		}

		//	检测游戏是否可以下载
		private function CheckDownLoadGame():void
		{
			//	如果有需要加载的文件，则
			if(AnsheGlobal.CheckSWFLoader(this.acsSprite.gameArray, this.swfPath))
			{
				isLoadDone = true;								
				
				if(initServerDone)
				{
					mcWait.visible = false;

					this.acsSprite.gameArray.push(this.swfPath);
					LoadFiles(this.swfPath + ".swf");
				}
				else
				{
					this.swfLoader.statue = "Link to server....";
				}
			}
			else
			{
				this.initSwfDone = true;
				
				if(this.initRoomDone && this.initSwfDone)
				{
					DeleteSWF();
				}
			}
		}

		//------------------- 公用方法 ------------------------------

		//	显示 出错 提示
		private function traceError(...argc):void
		{
			if(this.fDebug is DisplayObject)
			{
				this.fDebug.traceError(argc);
			}
		}
		
		//	显示 信息 提示
		private function traceInfo(...argc):void
		{
			if(this.fDebug is DisplayObject)
			{
				this.fDebug.traceInfo(argc);
			}
		}

		//	显示 消息提示
		private function traceMessage(...argc):void
		{
			if(this.fDebug is DisplayObject)
			{
				this.fDebug.traceMessage(argc);
			}
		}

		//------------------- ClientWidget 专用方法 ------------------------------
		
		//	重写基类中消息派发命令，指定消息必须由 space 进行发送及接收
		public function fireRemoteEvent(type:String, args:Object=null, recipients:Array=null, global:Boolean=false):void
		{
			traceError("Send IMVU command::  type -> " + type);			
		}
		
		//	删除 SWF 
		private function DeleteSWF():void
		{
			DeleteListener();
			
			this.parent.removeChild(this);
		}
		
		private function DeleteListener():void
		{
			this.swfLoader.parent.removeChild(this.swfLoader);
		}	
	}
}